<template>
  <div class="join-course-container">
    <h2 class="text-2xl font-bold mb-6">加入课程</h2>

    <!-- 表单 -->
    <form @submit.prevent="submitJoinCourse" class="max-w-md mx-auto space-y-4">
      <!-- 课程编号输入框 -->
      <div class="form-group">
        <label for="courseId" class="block text-sm font-medium text-gray-700 mb-1">课程编号</label>
        <input
          id="courseId"
          v-model="courseId"
          type="text"
          required
          placeholder="请输入要加入的课程编号"
          class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      <!-- 提交按钮 -->
      <div class="flex justify-between mt-6">
        <button type="button" class="btn btn-secondary" @click="goBack">取消</button>
        <button type="submit" class="btn btn-primary">提交加入</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';

const router = useRouter();
const userStore = useUserStore();

// 输入的课程编号
const courseId = ref('');

// 获取当前用户 ID
const userId = userStore.user?.userId || '';

// 返回上一页
function goBack() {
  router.back();
}

// 提交加入课程请求
async function submitJoinCourse() {
  if (!courseId.value.trim()) {
    alert('请输入有效的课程编号');
    return;
  }

  try {
    const response = await axios.post('/api/courses/enroll', {
      userId,
      courseId: courseId.value
    });

    if (response.status === 200) {
      alert('加入课程成功！');
      router.push(`/course/${courseId.value}`); // 跳转到课程详情页
    }
  } catch (error) {
    console.error('加入课程失败:', error);
    alert('加入课程失败，请检查是否已经加入课程');
  }
}
</script>

<style scoped>
.join-course-container {
  padding: 2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.btn {
  padding: 0.6rem 1.2rem;
  font-size: 1rem;
  border-radius: 0.375rem;
  font-weight: bold;
  transition: background-color 0.2s ease;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
  border: none;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  background-color: #f3f4f6;
  color: #374151;
  border: 1px solid #e5e7eb;
  cursor: pointer;
}

.btn-secondary:hover {
  background-color: #e5e7eb;
}
</style>